﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Xml.Linq;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace PhysicsSimulator.Game.AiLaTrieuPhu
{
    public partial class PlayGamePage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;
        UIElementRenderer elementRenderer;

        const string FILE = "Game/AiLaTrieuPhu/GameData.xml";
        const int MAX_QUESTION = 50;
        string _type = "";
        int _number_question;
        List<Question> _questions = new List<Question>();
        public PlayGamePage()
        {
            InitializeComponent();

            contentManager = (Application.Current as App).Content;

            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += timer_Update;
            timer.Draw += timer_Draw;

            LayoutUpdated += new EventHandler(XNARendering_LayoutUpdated);
        }

        void XNARendering_LayoutUpdated(object sender, EventArgs e)
        {
            // make sure page size is valid
            if (ActualWidth == 0 || ActualHeight == 0)
                return;

            // see if we already have the right sized renderer
            if (elementRenderer != null &&
                elementRenderer.Texture != null &&
                elementRenderer.Texture.Width == (int)ActualWidth &&
                elementRenderer.Texture.Height == (int)ActualHeight)
            {
                return;
            }

            // dispose the current renderer
            if (elementRenderer != null)
                elementRenderer.Dispose();

            // create the renderer
            elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
        }

        bool fist_load = true;
        int selectItem;
        int number_right;
        float score;
        float score_break;
        int time_phut;
        int time_giay;
        float _time;
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (fist_load)
            {
                NavigationContext.QueryString.TryGetValue("type", out _type);
                _number_question = int.Parse(_type);

                _time = 0;
                number_right = 0;
                score_break = 10f / _number_question;

                List<String> listQuestion = new List<String>();
                for (int i = _number_question; i >0; i--)
                {
                    String qt = "Câu hỏi " + (i).ToString();
                    listQuestion.Add(qt);
                }

                list_question.ItemsSource = listQuestion;
                selectItem = _number_question - 1;
                list_question.SelectedIndex = selectItem;
                list_question.ScrollIntoView(selectItem);
                list_question.UpdateLayout();

                ReadXMLFileXe(_number_question);

                cauhoiTextBlock.Text = _questions.First().question;
                dapanA.Content = _questions[selectItem].DA1;
                dapanB.Content = _questions[selectItem].DA2;
                dapanC.Content = _questions[selectItem].DA3;
                dapanD.Content = _questions[selectItem].DA4;

                SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

                spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);
                fist_load = false;
            }

            timer.Start();
            base.OnNavigatedTo(e);
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            timer.Stop();
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }
        void timer_Update(object sender, GameTimerEventArgs e)
        {
            _time += (float)e.ElapsedTime.TotalMilliseconds / 1000;
            time_phut = (int)_time / 60;
            time_giay = ((int)_time % 60);

            string phut = "";
            string giay = "";

            if (time_phut >= 10)
            {
                phut = time_phut.ToString();
            }
            else
            {
                phut = "0" + time_phut.ToString();
            }

            if (time_giay >= 10)
            {
                giay = time_giay.ToString();
            }
            else
            {
                giay = "0" + time_giay.ToString();
            }

            time.Text = phut + ":" + giay;
        }

        void timer_Draw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.White);
            elementRenderer.Render();
            spriteBatch.Begin();
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
            spriteBatch.End();
        }
        private void ReadXMLFileXe(int number)
        {
            Random random = new Random();
            XDocument data = XDocument.Load(FILE);
            //listbus.Items.Clear();
            for (int i = 0; i < number; i++)
            {
                string tmp_item = "_" + random.Next(1,MAX_QUESTION).ToString();
                var definitions = data.Document.Descendants(tmp_item);
                foreach (var animationDefinition in definitions)
                {
                    Question x = new Question();
                    x.question = animationDefinition.Attribute("CauHoi").Value;
                    x.DA1 = animationDefinition.Attribute("DA1").Value;
                    x.DA2 = animationDefinition.Attribute("DA2").Value;
                    x.DA3 = animationDefinition.Attribute("DA3").Value;
                    x.DA4 = animationDefinition.Attribute("DA4").Value;
                    x.DA = int.Parse(animationDefinition.Attribute("DA").Value);
                    _questions.Add(x);
                }
            }
        }

        private void dapanA_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            if (_questions[selectItem].DA == 1)
            {
                number_right++;
                score += score_break;
            }
            if (selectItem > 0)
            {
                selectItem--;
                list_question.SelectedIndex = selectItem;
                list_question.ScrollIntoView(selectItem);
                cauhoiTextBlock.Text = _questions[selectItem].question;
                dapanA.Content = _questions[selectItem].DA1;
                dapanB.Content = _questions[selectItem].DA2;
                dapanC.Content = _questions[selectItem].DA3;
                dapanD.Content = _questions[selectItem].DA4;
            }
            else
            {
                timer.Stop();
                if (MessageBox.Show("Số câu đúng: " + number_right.ToString() + "/" + _number_question.ToString() + "\nThời gian: " + time.Text + "\nĐiểm:" + score.ToString(), "KẾT QUẢ", MessageBoxButton.OK) == MessageBoxResult.OK)
                {
                    NavigationService.GoBack();
                }
                
            }
        }

        private void dapanB_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            if (_questions[selectItem].DA == 2)
            {
                number_right++;
                score += score_break;
            }
            if (selectItem > 0)
            {
                selectItem--;
                list_question.SelectedIndex = selectItem;
                list_question.ScrollIntoView(selectItem);
                cauhoiTextBlock.Text = _questions[selectItem].question;
                dapanA.Content = _questions[selectItem].DA1;
                dapanB.Content = _questions[selectItem].DA2;
                dapanC.Content = _questions[selectItem].DA3;
                dapanD.Content = _questions[selectItem].DA4;
            }
            else
            {
                timer.Stop();
                if (MessageBox.Show("Số câu đúng: " + number_right.ToString() + "/" + _number_question.ToString() + "\nThời gian: " + time.Text + "\nĐiểm:" + score.ToString(), "KẾT QUẢ", MessageBoxButton.OK) == MessageBoxResult.OK)
                {
                    NavigationService.GoBack();
                }
            }
        }

        private void dapanC_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            if (_questions[selectItem].DA == 3)
            {
                number_right++;
                score += score_break;
            }
            if (selectItem > 0)
            {
                selectItem--;
                list_question.SelectedIndex = selectItem;
                list_question.ScrollIntoView(selectItem);
                cauhoiTextBlock.Text = _questions[selectItem].question;
                dapanA.Content = _questions[selectItem].DA1;
                dapanB.Content = _questions[selectItem].DA2;
                dapanC.Content = _questions[selectItem].DA3;
                dapanD.Content = _questions[selectItem].DA4;
            }
            else
            {
                timer.Stop();
                if (MessageBox.Show("Số câu đúng: " + number_right.ToString() + "/" + _number_question.ToString() + "\nThời gian: " + time.Text + "\nĐiểm:" + score.ToString(), "KẾT QUẢ", MessageBoxButton.OK) == MessageBoxResult.OK)
                {
                    NavigationService.GoBack();
                }
            }
        }

        private void dapanD_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            if (_questions[selectItem].DA == 4)
            {
                number_right++;
                score += score_break;
            }
            if (selectItem > 0)
            {
                selectItem--;
                list_question.SelectedIndex = selectItem;
                list_question.ScrollIntoView(selectItem);
                cauhoiTextBlock.Text = _questions[selectItem].question;
                dapanA.Content = _questions[selectItem].DA1;
                dapanB.Content = _questions[selectItem].DA2;
                dapanC.Content = _questions[selectItem].DA3;
                dapanD.Content = _questions[selectItem].DA4;
            }
            else
            {
                timer.Stop();
                if (MessageBox.Show("Số câu đúng: " + number_right.ToString() + "/" + _number_question.ToString() + "\nThời gian: " + time.Text + "\nĐiểm:" + score.ToString(), "KẾT QUẢ", MessageBoxButton.OK) == MessageBoxResult.OK)
                {
                    NavigationService.GoBack();
                }
            }
        }
    }
}